package com.example.shangjiba;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 头像管理工具类
 * 负责头像的保存、加载、删除等操作
 */
public class AvatarManager {
    
    private static final String TAG = "AvatarManager";
    private static final String AVATAR_DIR = "avatars";
    private static final int MAX_IMAGE_SIZE = 800; // 压缩后的最大尺寸
    private static final int JPEG_QUALITY = 85; // JPEG压缩质量
    
    private final Context context;

    public AvatarManager(Context context) {
        this.context = context.getApplicationContext();
    }

    /**
     * 获取头像存储目录
     */
    private File getAvatarDirectory() {
        File avatarDir = new File(context.getFilesDir(), AVATAR_DIR);
        if (!avatarDir.exists()) {
            avatarDir.mkdirs();
        }
        return avatarDir;
    }

    /**
     * 获取用户头像文件
     */
    private File getUserAvatarFile(String userEmail) {
        String fileName = "avatar_" + userEmail.hashCode() + ".jpg";
        return new File(getAvatarDirectory(), fileName);
    }

    /**
     * 保存头像
     * @param userEmail 用户邮箱
     * @param imageUri 图片Uri
     * @return 是否保存成功
     */
    public boolean saveAvatar(String userEmail, Uri imageUri) {
        try {
            // 删除旧头像
            deleteAvatar(userEmail);
            
            // 加载并压缩图片
            InputStream inputStream = context.getContentResolver().openInputStream(imageUri);
            if (inputStream == null) {
                Log.e(TAG, "无法打开图片流");
                return false;
            }
            
            Bitmap originalBitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
            
            if (originalBitmap == null) {
                Log.e(TAG, "图片解码失败");
                return false;
            }
            
            // 压缩图片
            Bitmap compressedBitmap = compressBitmap(originalBitmap);
            
            // 保存到文件
            File avatarFile = getUserAvatarFile(userEmail);
            FileOutputStream fos = new FileOutputStream(avatarFile);
            compressedBitmap.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, fos);
            fos.flush();
            fos.close();
            
            // 释放资源
            if (compressedBitmap != originalBitmap) {
                compressedBitmap.recycle();
            }
            originalBitmap.recycle();
            
            Log.d(TAG, "头像保存成功: " + avatarFile.getAbsolutePath());
            return true;
            
        } catch (IOException e) {
            Log.e(TAG, "保存头像失败", e);
            return false;
        }
    }

    /**
     * 压缩Bitmap
     */
    private Bitmap compressBitmap(Bitmap original) {
        int width = original.getWidth();
        int height = original.getHeight();
        
        // 如果图片尺寸小于最大值，直接返回
        if (width <= MAX_IMAGE_SIZE && height <= MAX_IMAGE_SIZE) {
            return original;
        }
        
        // 计算缩放比例
        float scale;
        if (width > height) {
            scale = (float) MAX_IMAGE_SIZE / width;
        } else {
            scale = (float) MAX_IMAGE_SIZE / height;
        }
        
        int newWidth = (int) (width * scale);
        int newHeight = (int) (height * scale);
        
        return Bitmap.createScaledBitmap(original, newWidth, newHeight, true);
    }

    /**
     * 加载头像
     * @param userEmail 用户邮箱
     * @return Bitmap对象，如果不存在则返回null
     */
    public Bitmap loadAvatar(String userEmail) {
        File avatarFile = getUserAvatarFile(userEmail);
        if (avatarFile.exists()) {
            try {
                Bitmap bitmap = BitmapFactory.decodeFile(avatarFile.getAbsolutePath());
                Log.d(TAG, "头像加载成功: " + avatarFile.getAbsolutePath());
                return bitmap;
            } catch (Exception e) {
                Log.e(TAG, "加载头像失败", e);
                return null;
            }
        }
        Log.d(TAG, "头像文件不存在: " + avatarFile.getAbsolutePath());
        return null;
    }

    /**
     * 删除头像
     * @param userEmail 用户邮箱
     */
    public void deleteAvatar(String userEmail) {
        File avatarFile = getUserAvatarFile(userEmail);
        if (avatarFile.exists()) {
            if (avatarFile.delete()) {
                Log.d(TAG, "旧头像已删除: " + avatarFile.getAbsolutePath());
            }
        }
    }

    /**
     * 检查头像是否存在
     * @param userEmail 用户邮箱
     * @return 是否存在
     */
    public boolean hasAvatar(String userEmail) {
        return getUserAvatarFile(userEmail).exists();
    }
}

